// Coze API 服务封装

export class CozeChat {
  constructor(botId, userId, accessToken) {
    this.botId = botId;
    this.userId = userId;
    this.accessToken = accessToken;
    this.currentEvent = null;
    this.apiUrl = 'https://api.coze.cn/v3/chat';
    this.conversationApiUrl = 'https://api.coze.cn/v1/conversation';
  }

  async createConversation(messages = [], metaData = {}) {
    try {
      const response = await fetch(`${this.conversationApiUrl}/create`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${this.accessToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          messages: messages.map(msg => ({
            role: msg.role || 'user',
            content: msg.content,
            content_type: msg.content_type || 'text',
            type: msg.type || 'question',
            meta_data: msg.meta_data
          })),
          meta_data: metaData
        })
      });

      if (!response.ok) {
        throw new Error('创建会话失败: ' + response.statusText);
      }

      const result = await response.json();
      
      if (result.code !== 0) {
        throw new Error('创建会话失败: ' + result.msg);
      }

      return result.data;
    } catch (error) {
      throw new Error('创建会话请求失败: ' + error.message);
    }
  }

  async sendMessage(message, onMessageCallback, onErrorCallback, conversationId = null) {
    const messages = [
      {
        role: 'user',
        content: message,
        content_type: 'text'
      }
    ];

    try {
      await this.startChat(messages, onMessageCallback, conversationId);
    } catch (error) {
      if (onErrorCallback) {
        onErrorCallback(error); 
      }
    }
  }

  async startChat(messages, onMessageCallback, conversationId = null) {
    this.currentEvent = null;

    try {
      const response = await fetch(this.apiUrl + (conversationId ? `?conversation_id=${conversationId}` : ''), {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${this.accessToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          bot_id: this.botId,
          user_id: this.userId,
          stream: true,
          auto_save_history: true,
          additional_messages: messages
        })
      });

      if (!response.ok) {
        throw new Error('对话初始化失败: ' + response.statusText);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      let textBuffer = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        textBuffer += decoder.decode(value, { stream: true });

        const lines = textBuffer.split('\n');
        textBuffer = lines.pop(); // 保留最后一个可能不完整的行

        for (const line of lines) {
          if (line.trim()) {
            this.processLine(line.trim(), onMessageCallback);
          }
        }
      }

      if (textBuffer.trim()) {
        this.processLine(textBuffer.trim(), onMessageCallback);
      }

    } catch (error) {
      throw new Error('请求发生错误: ' + error.message);
    }
  }

  processLine(line, onMessageCallback) {
    try {
      if (line.startsWith('event:')) {
        this.currentEvent = line.slice(6).trim();
      } else if (line.startsWith('data:')) {
        if (!this.currentEvent) {
          console.error('缺少事件类型的数据行:', line);
          return;
        }
        
        const eventData = JSON.parse(line.slice(5).trim());

        if (this.currentEvent === 'conversation.message.delta') {
          if (eventData.role === 'assistant' && eventData.content_type === 'text') {
            onMessageCallback(eventData.content);
          }
          // 更新会话ID
          if (eventData.conversation_id) {
            this.currentConversationId = eventData.conversation_id;
          }
        } else if (this.currentEvent === 'conversation.chat.failed') {
          throw new Error('对话失败: ' + JSON.stringify(eventData));
        }
        
        this.currentEvent = null;
      }
    } catch (error) {
      console.error('解析数据时发生错误', error, line);
      throw error;
    }
  }
}

// 导出一个用于创建聊天实例的工厂函数
export function createChatInstance(botId, userId, accessToken) {
  return new CozeChat(botId, userId, accessToken);
}



// 导出润色文本的函数
export async function polishText(text, onProgressCallback) {
  // 创建聊天实例
  const botId = '7474140345551863834';
  const userId = 'sheliming';
  const accessToken = 'pat_ugtJNBYOtBsPwdeY4JbO5WFVT9GzpOK7xgXnUcgTF2FdWyNbNzvhrHqW0OwsoXb6';
  const chatInstance = createChatInstance(botId, userId, accessToken);

  // 构建润色提示词
  const prompt = `请帮我润色以下剧本，使其更加生动有趣，同时保持原有的故事情节不变：\n\n${text}`;

  let polishedText = '';
  
  // 发送消息并通过回调函数更新润色结果
  await chatInstance.sendMessage(
    prompt,
    (content) => {
      polishedText += content;
      if (onProgressCallback) {
        onProgressCallback(polishedText);
      }
    },
    (error) => {
      throw error;
    },
    null
  );

  return polishedText;
}

// 导出对话函数
export async function chat(text, onProgressCallback, conversationId = null) {
  // 创建聊天实例
  const botId = '7473461301369667603';
  const userId = 'sheliming';
  const accessToken = 'pat_ugtJNBYOtBsPwdeY4JbO5WFVT9GzpOK7xgXnUcgTF2FdWyNbNzvhrHqW0OwsoXb6';
  const chatInstance = createChatInstance(botId, userId, accessToken);

  let currentConversationId = conversationId;
  
  // 如果没有会话ID，创建新会话
  if (!currentConversationId) {
    try {
      const conversation = await chatInstance.createConversation();
      currentConversationId = conversation.conversation_id;
    } catch (error) {
      throw new Error('创建会话失败: ' + error.message);
    }
  }

  let responseText = '';
  
  // 发送消息并通过回调函数更新对话内容
  try {
    await chatInstance.sendMessage(
      text,
      (content) => {
        responseText += content;
        if (onProgressCallback) {
          onProgressCallback(responseText);
        }
      },
      (error) => {
        throw error;
      },
      currentConversationId
    );

    // 返回会话ID和响应文本
    return {
      conversationId: currentConversationId,
      response: responseText
    };
  } catch (error) {
    console.error('发送消息失败:', error);
    throw error;
  }
}

// 导出主持人对话函数
export async function hostChat(text, onProgressCallback, conversationId = null) {
  // 创建聊天实例
  const botId = '7475692342180380698';
  const userId = 'sheliming';
  const accessToken = 'pat_ugtJNBYOtBsPwdeY4JbO5WFVT9GzpOK7xgXnUcgTF2FdWyNbNzvhrHqW0OwsoXb6';
  const chatInstance = createChatInstance(botId, userId, accessToken);

  let currentConversationId = conversationId;
  console.log('传入的会话ID:', currentConversationId);
  
  // 如果没有会话ID，创建新会话
  if (!currentConversationId) {
    try {
      const conversation = await chatInstance.createConversation();
      console.log('conversation:', conversation);
      currentConversationId = conversation.id;
    } catch (error) {
      throw new Error('创建会话失败: ' + error.message);
    }
  }
  console.log('创建会话的会话ID:', currentConversationId);

  let responseText = '';
  
  // 发送消息并通过回调函数更新对话内容
  try {
    await chatInstance.sendMessage(
      text,
      (content) => {
        responseText += content;
        if (onProgressCallback) {
          onProgressCallback(responseText);
        }
      },
      (error) => {
        throw error;
      },
      currentConversationId
    );
    
    // 返回会话ID和响应文本
    return {
      conversationId: currentConversationId,
      response: responseText
    };
  } catch (error) {
    console.error('发送消息失败:', error);
    throw error;
  }
}